from django.shortcuts import render

# Create your views here.
from django.views.generic import View
from book.models import BookInfo
from django.http import JsonResponse
import json

# Create your views here.
class BookListView(View):
    """
    查询所有图书、增加图书
    """
    def get(self, request):
        """
        查询所有图书
        路由：GET /books/
        """
        queryset = BookInfo.objects.all()
        book_list = []
        for book in queryset:
            book_list.append({
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date
            })
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book = BookInfo.objects.create(
            name=book_dict.get('name'),
            pub_date=book_dict.get('pub_date')
        )

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        },safe=False)

class BookDetailView(View):
    """
    获取单个图书信息
    修改图书信息
    删除图书
    """
    def get(self, request, pk):
        """
        获取单个图书信息
        路由： GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def put(self, request, pk):
        """
        修改图书信息
        路由： PUT  /books/<pk>
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book.name = book_dict.get('name')
        book.pub_date = book_dict.get('pub_date')
        book.save()

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def delete(self, request, pk):
        """
        删除图书
        路由： DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        book.delete()

        return JsonResponse({},status=204)




###############################################################
from book.serializers import  BookInfoSerializer
from book.models import BookInfo
# 1.模拟查询一个对象
book= BookInfo.objects.get(id=1)
#2 实例化序列化.将对象数据传递给序列化器
serializer=BookInfoSerializer(instance=book)
# 3 获取序列化器 将对象转化为字典的数据
serializer.data


#########多条数据的查询集QuerySet#####
from book.serializers import  BookInfoSerializer
from book.models import BookInfo

#1. 获取所有书籍
books=BookInfo.objects.all()
# 2. 实例化序列化,将对象传给序列化
serializer=BookInfoSerializer(instance=books,many=True)
# 3 .获取序列化(将对象转为字典数据)
serializer.data

########定义外键的序列化器的定义 验证#####
from book.serializers import PeopleInfoSerializer
from book.models import PeopleInfo

# 1.  模拟查询对象
person=PeopleInfo.objects.get(id=1)

# 2. 创建序列化器
serializer=PeopleInfoSerializer(instance=person)

# 3. 获取序列化器中 将对象转换为字典的数据
serializer.data






# ####################################将字典转化为对对象
from book.serializers import BookInfoSerializer

# 1模拟字典数据
data={
    'name':'django',
    'pub_date':'2018-器材草1-1',
    'readcount':666


}
# 创建序列化器 将字典数据传给序列化器
# instance 用于序列化(对象转换为字典)  data 用于反序列化(字典转换为对象)
serializer=BookInfoSerializer(data=data)
serializer.is_valid(raise_exception=True)



